<template>
	<view class="interview_content">
		<view class="basic_information">
			<view class="interview_title">Basic Information</view>
			<view class="basic_viewst">
				<view class="basic_item">
					<text>Student Name</text>
					<input type="text" placeholder-class="font-color" placeholder="Please enter..." v-model="userName" />
				</view>
				<view class="basic_item">
					<text>Visit Date & Time</text>
					<view class="time_content">
						<view class="tab" :style="{ color: times != 'Select time...' ? '#555' : '#0faeff' }" @tap="toggleTab">{{ times }}</view>
						<w-picker
							mode="date"
							startYear="2019"
							endYear="2030"
							step="1"
							:defaultVal="[1, 1, 1, 1, 2, 5]"
							:current="true"
							@confirm="onConfirm"
							@tap="hideKey"
							ref="date"
							themeColor="#f00"
						></w-picker>
					</view>
				</view>
				<view class="basic_item">
					<text>School Name</text>
					<input type="text" placeholder-class="font-color" placeholder="Please enter..." v-model="schoolName" />
				</view>
				<view class="basic_item">
					<text>Year Level</text>
					<input type="text" placeholder-class="font-color" placeholder="Please enter..." v-model="annualLevel" />
				</view>
				<view class="basic_item" style="flex-direction: column;">
					<text>Homestay Address （If knows）</text>
					<input type="text" style="width: 100%; text-align: left; margin-top: 10px;" placeholder-class="font-color" placeholder="Please enter..." v-model="address" />
				</view>
				<view class="basic_item" style="flex-direction: column;">
					<text>Homestay Contact ( If knows )</text>
					<input type="text" style="width: 100%; text-align: left; margin-top: 10px;" placeholder-class="font-color" placeholder="Please enter..." v-model="connection" />
				</view>
			</view>
		</view>
		<view class="interview_information">
			<view class="interview_title">Interview information</view>
			<view class="s_information">
				<view class="s_title">Student's Concern At School：</view>
				<textarea v-model="stuAtSchool" placeholder="Please enter..." />
			</view>
			<view class="s_information">
				<view class="s_title">Student's Concern At Homestay：</view>
				<textarea v-model="stuAtHomestay" placeholder="Please enter..." />
			</view>
		</view>
		<view class="signature">
			<view class="interview_title">Signature</view>
			<view style="padding: 15px; box-sizing: border-box;">
				<view class="s_title">Student's Signature</view>
				<image v-show="isShowSignature" :src="signImage"></image>
				<image style="width: 60px; height: 60px;" @tap="studentSignature" src="../../static/img/add_pic.png"></image>
				<view class="contents" v-if="isSignature">
					<canvas
						class="firstCanvas"
						canvas-id="firstCanvas"
						@touchmove="move"
						@touchstart="start($event)"
						@touchend="end"
						@touchcancel="cancel"
						@longtap="tap"
						disable-scroll="true"
						@error="error"
					></canvas>
					<view class="caozuo">
						<view class="chongqian" @tap="clearClick">Reset</view>
						<view class="over" @tap="overSign">Done</view>
					</view>
				</view>
			</view>
			<view style="padding: 15px; box-sizing: border-box;">
				<view class="s_title">Manager's Photograph</view>
				<image v-show="isPhotoPath" :src="photoPath"></image>
				<image style="width: 60px; height: 60px;" @tap="photo" src="../../static/img/add_pic.png"></image>
			</view>
		</view>
		<button type="warn" class="bottom_btn" @tap="addRecord">Submit</button>
	</view>
</template>

<script>
import wPicker from '@/components/w-picker/w-picker.vue';
var content = null;
var touchs = [];
var canvasw = 0;
var canvash = 0;
var _that;
//获取系统信息
uni.getSystemInfo({
	success: function(res) {
		canvasw = res.windowWidth;
		canvash = res.windowHeight;
	}
});

import api from '../../api/recordApi.js';
import utils from '../../api/utils.js';

export default {
	components: {
		wPicker
	},
	data() {
		return {
			// 姓名
			userName: '',
			// 访谈时间
			times: 'Select time...',
			// 学校名
			schoolName: '',
			// 年度水平
			annualLevel: '',
			// 寄宿地址
			address: '',
			// 寄宿关系
			connection: '',
			// 学生对学校的关注
			stuAtSchool: '',
			// 学生对寄宿家庭的关注
			stuAtHomestay: '',
			isSignature: false,
			signImage: '',
			isEnd: false, // 是否签名
			// 合照路径
			photoPath: '',
			isPhotoPath: false,
			isShowSignature: false,
			// 签名路径
			signaturePath: '',
			// 监护人id
			intId: '',
			// 学生id
			stuId: '',
			// 上传合照路径
			upPhotoPath: '',
			// 上传签名路径
			upSignImage: '',
			token: ''
		};
	},
	mounted() {
		// methods里面定义的方法, 需要赋值给Vue
		Vue.prototype.$uploadImage = this.uploadImage;
	},
	methods: {
		async uploadImage(input) {
			var UserDefaultsClass = plus.ios.importClass('NSUserDefaults');
			let standardUserDefaults = UserDefaultsClass.standardUserDefaults();
			let imageBase64 = plus.ios.invoke(standardUserDefaults, 'objectForKey:', 'SigningBase64');
			console.warn('imageBase64 is is is' + imageBase64);

			plus.ios.invoke(standardUserDefaults, 'removeObjectForKey:', 'SigningBase64');
			plus.ios.invoke(standardUserDefaults, 'synchronize');

			
			let _this = this;
			let data = await api.upLoadBase64(imageBase64)
			if (data.head.status) {
				if (input == 'sign'){
					//设置图片
					_this.isSignature = false;
					_this.isShowSignature = true;
					// 把data.body.picturePath替换成你接口返回的签名路径就好了
					_this.upSignImage = data.body.picturePath;
					_this.signImage = `${utils.localURL}/${data.body.picturePath.replace(/\\/g, '/')}`;
					console.log(_this.signImage, 2222);
				}
				else{
					_this.upPhotoPath = data.body.picturePath;
					_this.photoPath = `${utils.localURL}/${_this.upPhotoPath.replace(/\\/g, '/')}`;
					_this.isPhotoPath = true;
				}
			} else {
				uni.showToast({
					title: data.head.msg,
					icon: 'none',
					duration: 1000
				});
			}

		},
		hideKey() {
			setTimeout(() => {
				uni.hideKeyboard();
			}, 200);
		},
		// 添加访谈结果
		async addRecord() {
			let _this = this;
			let obj = {
				userName: _this.userName,
				times: _this.times,
				schoolName: _this.schoolName,
				annualLevel: _this.annualLevel,
				address: _this.address,
				connection: _this.connection,
				stuAtSchool: _this.stuAtSchool,
				stuAtHomestay: _this.stuAtHomestay
			};
			if (
				!obj.userName ||
				obj.times == 'Select time...' ||
				!obj.schoolName ||
				!obj.annualLevel ||
				!obj.address ||
				!obj.connection ||
				!obj.stuAtSchool ||
				!obj.stuAtHomestay ||
				!_this.upSignImage ||
				!_this.upPhotoPath
			) {
				uni.showToast({
					title: 'Please complete the form information！',
					icon: 'none',
					duration: 2000
				});
				return false;
			}

			uni.showLoading({
				title: 'Please wait...',
				mask: true
			});
			let jsonStr = JSON.stringify(obj).replace(/\"/g, '\\"');
			console.log(_this.upPhotoPath);
			console.log(_this.upSignImage);
			let data = await api.addRecord(
				'problemresult/addGruSysProblemResult',
				{
					problemResultGroupPhotoPath: _this.upPhotoPath,
					problemResultGuardianId: _this.intId,
					problemResultObject: jsonStr,
					problemResultSignPath: _this.upSignImage,
					problemResultStuId: _this.stuId
				},
				_this.token
			);
			if (data.head.status) {
				uni.showToast({
					title: 'Success！',
					duration: 1000
				});
				setTimeout(() => {
					uni.redirectTo({
						url: '../searchRecord/searchList'
					});
				}, 1500);
			} else {
				uni.showToast({
					title: data.head.msg,
					icon: 'none',
					duration: 1000
				});
			}
			uni.hideLoading();
		},

		// 合照
		photo() {
			let _this = this;
			uni.chooseImage({
				count: 1, //默认9
				sizeType: ['original', 'compressed'],
				sourceType: ['camera'],
				success: function(res) {
					if(plus.os.name == 'iOS'){
						//打印图片路径
						let path = 'Pandora/apps/__UNI__B29C11E/' + res.tempFilePaths[0].substr(1, res.tempFilePaths[0].length - 1);
						var notiClass = plus.ios.importClass('NSNotificationCenter');
						notiClass.defaultCenter().postNotificationNameobject('PhotoToBase64', path);
					}
					else {
						uni.uploadFile({
							url: `${utils.localURL}/picture/uploadFile`,
							filePath: res.tempFilePaths[0],
							name: 'inputText',
							formData: {
								randomKey: '',
								pictureType: ''
							},
							success: uploadFileRes => {
								let data = JSON.parse(uploadFileRes.data);
								console.log(data);
								if (data.head.status) {
									_this.upPhotoPath = data.body.picturePath;
									_this.photoPath = `${utils.localURL}/${_this.upPhotoPath.replace(/\\/g, '/')}`;
									_this.isPhotoPath = true;
								} else {
									uni.showToast({
										title: data.head.msg,
										icon: 'none',
										duration: 1000
									});
								}
							},
							fail(err) {
								console.log(err);
							}
						});
					}
				}
			});
		},
		// 触发日期控件
		toggleTab() {
			this.$refs['date'].show();
		},
		// 选择日期控件
		onConfirm(data) {
			this.times = data.result;
		},
		// 点击签名按钮
		studentSignature() {
			this.isSignature = !this.isSignature;
		},
		// 完成签名
		overSign: function() {
			let _this = this;
			if (_this.isEnd) {
				uni.canvasToTempFilePath({
					canvasId: 'firstCanvas',
					success: function(res) {
						if(plus.os.name == 'iOS'){
							//打印图片路径
							let path = 'Pandora/apps/__UNI__B29C11E/' + res.tempFilePath.substr(1, res.tempFilePath.length - 1);
							var notiClass = plus.ios.importClass('NSNotificationCenter');
							notiClass.defaultCenter().postNotificationNameobject('ImageToBase64', path);
						}
						else{
							uni.uploadFile({
								url: `${utils.localURL}/picture/uploadFile`,
								filePath: res.tempFilePath,
								name: 'inputText',
								formData: {
									randomKey: '',
									pictureType: ''
								},
								success: uploadFileRes => {
									let data = JSON.parse(uploadFileRes.data)
									console.log(data)
									if (data.head.status) {
										//设置图片
										_this.isSignature = false;
										_this.isShowSignature = true;
										_this.upSignImage = data.body.picturePath
										_this.signImage = `${utils.localURL}/${data.body.picturePath.replace(/\\/g, '/')}`;
										console.log(_this.signImage, 2222)
									} else {
										uni.showToast({
											title: data.head.msg,
											icon: 'none',
											duration: 1000
										});
									}
								},
								fail(err) {
									console.log(err)
								}
							});
						}
					}
				});
			} else {
				uni.showToast({
					title: '请先完成签名',
					icon: 'none',
					duration: 1500,
					mask: true
				});
			}
		},

		// 画布的触摸移动开始手势响应
		start: function(event) {
			// console.log(event)
			// console.log('触摸开始' + event.changedTouches[0].x);
			// console.log('触摸开始' + event.changedTouches[0].y);
			//获取触摸开始的 x,y
			let point = {
				x: event.changedTouches[0].x,
				y: event.changedTouches[0].y
			};
			// console.log(point)
			touchs.push(point);
		},
		// 画布的触摸移动手势响应
		move: function(e) {
			let point = {
				x: e.touches[0].x,
				y: e.touches[0].y
			};
			// console.log(point)
			touchs.push(point);
			if (touchs.length >= 2) {
				this.draw(touchs);
			}
		},

		// 画布的触摸移动结束手势响应
		end: function(e) {
			// console.log('触摸结束' + e);
			// 设置为已经签名
			this.isEnd = true;
			// 清空轨迹数组
			for (let i = 0; i < touchs.length; i++) {
				touchs.pop();
			}
		},

		// 画布的触摸取消响应
		cancel: function(e) {
			console.log('触摸取消' + e);
		},

		// 画布的长按手势响应
		tap: function(e) {
			console.log('长按手势' + e);
		},

		error: function(e) {
			console.log('画布触摸错误' + e);
		},

		//绘制
		draw: function(touchs) {
			// console.log(touchs[0], touchs[1]);
			let point1 = touchs[0];
			let point2 = touchs[1];
			touchs.shift();
			content.moveTo(point1.x, point1.y);
			content.lineTo(point2.x, point2.y);
			content.stroke();
			content.draw(true);
		},
		//清除操作
		clearClick: function() {
			// 设置为未签名
			this.isEnd = false;
			//清除画布
			content.clearRect(0, 0, canvasw, canvash);
			content.draw(true);
		}
	},
	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function(options) {
		this.intId = options.intId;
		this.stuId = options.stuId;
		uni.getStorage({
			key: 'token',
			success(res) {
				_this.token = res.data;
			}
		});
		_that = this;
		//获得Canvas的上下文
		content = wx.createCanvasContext('firstCanvas');
		//设置线的颜色
		content.setStrokeStyle('#000');
		//设置线的宽度
		content.setLineWidth(5);
		//设置线两端端点样式更加圆润
		content.setLineCap('round');
		//设置两条线连接处更加圆润
		content.setLineJoin('round');
	}
};
</script>

<style scoped>
.interview_content {
	width: 100%;
	padding-bottom: 50px;
	box-sizing: border-box;
}

.interview_title {
	width: 100%;
	height: 45px;
	line-height: 45px;
	background-color: #f1f1f1;
	font-size: 14px;
	padding: 0 15px;
	box-sizing: border-box;
	color: #555;
}

.basic_viewst {
	padding: 0;
	margin: 0;
	viewst-style: none;
}

.basic_item {
	display: flex;
	justify-content: space-between;
	padding: 15px;
	font-size: 16px;
	border-bottom: soviewd 1px #f5f5f5;
}

.basic_item > text {
	color: #666;
}

.basic_item > input {
	text-align: right;
	width: 50%;
	color: #555;
}

.time_content {
	text-align: center;
}

.s_information {
	padding: 15px;
	box-sizing: border-box;
}

.s_title {
	font-size: 16px;
	color: #666;
	margin-bottom: 15px;
}

.s_information > textarea {
	width: 100%;
	height: 120px;
	font-size: 16px;
	color: #666;
	border: solid 1px #ddd;
	box-sizing: border-box;
	padding: 5px;
	border-radius: 5px;
}

.bottom_btn {
	width: 100%;
	height: 45px;
	line-height: 45px;
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
}

/* 时间插件样式 */
.tab {
	font-size: 16px;
}

.ts {
	color: #ff485d;
	font-size: 30upx;
	height: 100upx;
	line-height: 100upx;
	padding-left: 20upx;
}

canvas {
	background-color: #dddddd;
	width: 700upx;
	margin: 0 25upx;
	height: calc(100vh - 140upx);
}

.contents {
	padding-top: 20upx;
	padding-bottom: 100upx;
	box-sizing: border-box;
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	z-index: 999999;
}

#signatureImg {
	background-color: #eeeeee;
}

.caozuo {
	display: flex;
	height: 100upx;
	width: 750upx;
	position: fixed;
	left: 0;
	bottom: 0;
}

.caozuo view {
	width: 375upx;
	text-align: center;
	height: 100upx;
	line-height: 100upx;
	color: #ffffff;
}

.caozuo view:active {
	background-color: #cccccc;
	color: #333333;
}

.chongqian {
	background-color: #ff8f58;
}

.over {
	background-color: #0599d7;
}
</style>
